package com.sinszm.wechat.configuration;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 公共配置
 * @author chenjianbo
 * @date 2020-3-8
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(value = "com.sinszm.wechat.dao", transactionManagerRef = "jpaTransactionManager")
@EnableConfigurationProperties(WxProperties.class)
public class BasicConfiguration implements TransactionManagementConfigurer, WebMvcConfigurer {

    @Resource
    private DataSource dataSource;

    /**
     * JPA事务管理器
     */
    @Bean("jpaTransactionManager")
    public JpaTransactionManager jpaTransactionManager() {
        JpaTransactionManager jpa = new JpaTransactionManager();
        jpa.setDataSource(dataSource);
        jpa.setRollbackOnCommitFailure(true);
        return jpa;
    }

    @Override
    public TransactionManager annotationDrivenTransactionManager() {
        return jpaTransactionManager();
    }

    /**
     * 配置静态资源访问
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/webapp/");
    }
}